/*
 * Client.java
 *
 * Created on August 10, 2006, 1:16 PM
 *
 */
package org.letva.copie.client;

/**
 *
 * @author Vuk Nikolic
 */
import java.awt.datatransfer.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import org.letva.copie.client.gui.ClientWindow;
import org.letva.copie.common.message.*;
import org.letva.copie.common.message.Message;
import org.letva.copie.common.message.SubServerInfo;
import java.util.LinkedList;

public class Client {

	public Client(ClientWindow frame) {
		myWindow = frame;
	}

	public void openConnection(String host, int port) throws UnknownHostException,
			SocketTimeoutException, SocketException, IOException {
		subServerHost = host;
		subServerPort = port;
		mySocket = new Socket(host, port);
		mySocket.setSoTimeout(timeout);
		out = new ObjectOutputStream(mySocket.getOutputStream());
		in = new ObjectInputStream(mySocket.getInputStream());
		connectedToSubServer = true;
	}

	public void closeConnection() {
		try {
			out.close();
			in.close();
			mySocket.close();
		} catch (IOException e) {
			System.err.println("Couldn't get I/O");
			System.exit(1);
		}
	}

	public void copy(String fromUser) {
		StringSelection contents = new StringSelection(fromUser);
		myClipboard.setContents(contents, null);
	}

	public void paste() throws UnsupportedFlavorException, IOException {
		Transferable content = myClipboard.getContents(this);
		String s = (String) content.getTransferData(DataFlavor.stringFlavor);
		myWindow.getTextArea().replaceSelection(s);
	}

	public void cut(String s) throws Exception {
		copy(s);
		myWindow.getTextArea().replaceSelection("");
	}

	public LinkedList getLocalSubServers() {
		return subServers;
	}

	public LinkedList getSubServers() throws SocketException, SocketTimeoutException,
			ClassNotFoundException, IOException {
		// posalji zahtev za podserverima
		Object outputMessage = new Message("client", "server", "#list#");

		out.writeObject(outputMessage);
		out.flush();

		// kada primis upamti i time liste postaje dostupna korisniku
		Object inputMessage = in.readObject();
		subServers = (LinkedList) (((Message) inputMessage).getInfo());

		return subServers;
	}

	public Object[] convertSubServersToObjects(LinkedList ll) {
		Object[] objects = new Object[0];
		if (ll != null) {
			objects = new Object[ll.size()];
			for (int i = 0; i < ll.size(); i++) {
				SubServerInfo ssi = ((SubServerInfo) ll.get(i));
				String s = ssi.getUrl() + ":" + ssi.getSubServerPort();
				objects[i] = s;
			}

		}

		return objects;
	}

	public void pasteFrom(int i) throws SocketException, SocketTimeoutException,
			ClassNotFoundException, IOException {
		SubServerInfo ssi = (SubServerInfo) subServers.get(i);

		// posaljemo zahtev za cliboard.
		Object outputMessage = new Message("client", "server", "#pasteFrom#" + ssi.getUrl() + "#" + ssi.getSubServerPort());

		out.writeObject(outputMessage);
		out.flush();

		fromServer = in.readObject();

		if (fromServer != null) {

			String messageType = ((Message) fromServer).getType();
			if (messageType.equals("normal")) {
				// ovde pogledaj tip poruke koji se salje
				// da li je instance of String ili LinkedList
				// ako je String onda je samo tekst, ako je
				// LinkedList onda salje listu fajlova
				Object o = ((Message) fromServer).getInfo();
				if (o instanceof java.lang.String) {
					String s = (String) ((Message) fromServer).getInfo();

					myWindow.getTextArea().replaceSelection(s);
				}

				if (o instanceof java.util.LinkedList) {
					/* UZIMANJE IZ LISTE! */
					LinkedList fileInfoList = (LinkedList) o;
					String startDir = "";
					String dir = startDir;

					boolean dirCreated = (new File(dir)).mkdir();
					LinkedList newFiles = new LinkedList();

					FileInfo firstFileInfo = (FileInfo) fileInfoList.get(0);
					File firstFile = firstFileInfo.getFile();
					String oldStartPath = firstFile.getParent();


					// System.out.println(fileInfoList.size());

					for (int j = 0; j < fileInfoList.size(); j++) {

						FileInfo fileInfo = (FileInfo) fileInfoList.get(j);
						String newPath = fileInfo.getFile().getParent().replace(oldStartPath, "") + File.separator;
						newPath = newPath.substring(1);


						if (fileInfo.isFile()) {
							dir = startDir + newPath;
							File file = new File(dir + fileInfo.getName());
							newFiles.add(file);
							System.out.println(fileInfo.getFile().getPath());

							OutputStream out = new FileOutputStream(file);
							out.write(fileInfo.getBytes());
							out.close();

						}

						// System.out.println(fileInfo.getFile());
						if (fileInfo.isDirectory()) {
							dir = startDir + newPath + fileInfo.getName() + File.separator;

							//System.out.println("DIR " + dir);
							File newFile = new File(dir);
							newFiles.add(newFile);

							boolean b = newFile.mkdir();

						}

					}

					TransferableList tl = new TransferableList(newFiles);
					myClipboard.setContents(tl, null);
					myWindow.setDialog("LINKED LIST", ((Message) fromServer).getInfo().toString());
				}
			}
			if (messageType.equals("system")) {
				System.out.println("sistemska poruka: " + ((Message) fromServer).getInfo());

				myWindow.setDialog("Error", ((Message) fromServer).getInfo().toString());


			}
		}

	}

	public boolean isConnectedToSubServer() {
		return connectedToSubServer;
	}

	public String getSubServerHost() {
		return subServerHost;
	}

	public int getSubServerPort() {
		return subServerPort;
	}
	// prozor sa kojim je povezana aplikacija
	private ClientWindow myWindow;
	// sistemski klipboard sa kojim radimo
	private Clipboard myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	// za identifikaciju klijenata
	private static int totalId = 0;
	private int id = ++totalId;
	// socket na koji se povezuje sa (pod)serverom
	private Socket mySocket = null;
	// streamovi za citanje i pisanje sa servera i standardnog ulaza
	private ObjectOutput out = null;
	private ObjectInput in = null;
	// poruke sa servera i od korisnika.
	private Object fromServer = null;
	private String fromUser = null;
	private String subServerHost = "10.0.0.7";
	private int subServerPort = 7770;
	private LinkedList subServers = new LinkedList();
	private boolean connectedToSubServer = false;
	private int timeout = 10000;
}
